package com.qf.cx.simplenms.topic.tag;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.qf.cx.simplenms.reader.tag.Tag;
import com.qf.cx.simplenms.reader.tag.Tag.ReadOpResult;
import com.qf.cx.simplenms.reader.tag.Tag.VehicleInfo;
import com.qf.cx.simplenms.readergroup.tag.ReaderGroupTag;
import com.qf.cx.simplenms.readergroup.tag.ReaderGroupTags;
import com.qf.cx.simplenms.tagmemory.model.TagMemoryModel;
import com.qf.cx.simplenms.tagmemory.model.TagMemoryModel.Identifier;

public class TopicTagGenerator {
	private final Map<Identifier, TagMemoryModel> tagMemories = new HashMap<>();
	private Map<String, TopicTag> tid2Tag = new HashMap<>();

	public TopicTagGenerator(Set<TagMemoryModel> tagMemories) {
		for (TagMemoryModel e : tagMemories) {
			this.tagMemories.put(e.indentifier(), e);
		}
	}

	public synchronized void add(ReaderGroupTags readerGroupTags) {
		List<ReaderGroupTag> tags = readerGroupTags.getTags();
		for (ReaderGroupTag readerGroupTag : tags) {
			TopicTag topicTag = tid2Tag.get(readerGroupTag.getTid());
			if (topicTag != null) {
				topicTag.addReaderGroupName(readerGroupTags.getReaderGroupName());
				topicTag.mergeStatistics(readerGroupTag.getStatistics());
			} else {
				topicTag = new TopicTag();
				topicTag.addReaderGroupName(readerGroupTags.getReaderGroupName());
				topicTag.setAntenna(readerGroupTag.getAntenna());
				topicTag.setTag(generateTag(readerGroupTag.getTag()));
				topicTag.mergeStatistics(readerGroupTag.getStatistics());
				tid2Tag.put(readerGroupTag.getTid(), topicTag);
			}
		}
	}

	private Tag generateTag(Tag t) {
		Tag tag = new Tag();
		tag.setTid(t.getTid());
		tag.setDiscoveryTime(t.getDiscoveryTime());
		Map<Identifier, ReadOpResult> readOpResults = new HashMap<>();
		tag.setReadOpResults(readOpResults);
		for (Entry<Identifier, ReadOpResult> entry : t.getReadOpResults().entrySet()) {
			if (tagMemories.get(entry.getKey()) != null) {
				readOpResults.put(entry.getKey(), entry.getValue());
			}
		}

		for (Entry<Identifier, VehicleInfo> entry : t.getVehicleInfos().entrySet()) {
			if (tagMemories.get(entry.getKey()) != null) {
				tag.addVehicleInfo(entry.getKey(), entry.getValue());
			}
		}
		return tag;
	}

	public synchronized Collection<TopicTag> generate() {
		Collection<TopicTag> values = tid2Tag.values();
		tid2Tag = new HashMap<>();
		return values;
	}

}
